#!/bin/bash
################################################################################
#  Copyright (C) 2025 IQIYI All rights reserved.
#
#  Author     : 王海斌
#  E-mail     : wanghaibin@qiyi.com
#  Version    :
#  Date       : Thu 14 Aug 2025 09:53:48 AM CST
#  Destription: 对文件进行格式转换，去掉行尾的^M，并将文件转为utf-8格式
#              依赖工具 dos2unix 和 iconv
#
################################################################################
cd `dirname $0`

#  是否显示执行过程
#set -x 
# 检查必要工具是否安装
check_dependency() {
    if ! command -v "$1" >/dev/null 2>&1; then
        echo "错误: 未安装 '$1'，请先安装:"
        if [[ "$OSTYPE" == "linux-gnu"* ]]; then
            echo "  sudo apt-get install $1    # Debian/Ubuntu"
            echo "  或"
            echo "  sudo yum install $1        # CentOS/RHEL"
        elif [[ "$OSTYPE" == "darwin"* ]]; then
            echo "  brew install $1            # macOS (Homebrew)"
        else
            echo "  请参考系统文档安装 $1"
        fi
        exit 1
    fi
}

# 检查 dos2unix 和 iconv
check_dependency dos2unix
check_dependency iconv


# 检查参数
if [ $# -eq 0 ]; then
    echo "usage: $0 file1 [file2 ...]"
    echo "example: $0 *.cpp"
    exit 1
fi

# 遍历所有输入文件
for file in "$@"; do
    if [ ! -f "$file" ]; then
        echo "skip not exist '$file'"
        continue
    fi

    #echo "deal: $file"

    # 备份原文件（添加 .bak 后缀）
    backup="${file}.bak"
    cp -f "${file}" "${backup}" || { echo "can not create backup file '${backup}'"; exit 1; }

    # 1. 先用 dos2unix 处理换行符（自动跳过二进制文件）
    dos2unix "$file" 2>/dev/null
    if [ $? -ne 0 ]; then
		echo "dos2unix deal '$file' failed. (可能是二进制文件)"
	else
		rm -f ${backup}
    fi

    # 2. 再用 iconv 转换编码（GBK → UTF-8）
    tmpfile="${file}.tmp"
    iconv -f GBK -t UTF-8 "$file" -o "$tmpfile" 2>/dev/null
    if [ $? -eq 0 ]; then
        mv -f "$tmpfile" "$file"
        echo "complete: $file (GBK → UTF-8, CRLF → LF)"
    else
        echo "警告: '$file' 可能不是 GBK 编码，尝试其他编码..."
        # 尝试常见中文编码（GB18030 是 GBK 的超集）
        iconv -f GB18030 -t UTF-8 "$file" -o "$tmpfile" 2>/dev/null || \
        iconv -f UTF-8 -t UTF-8 "$file" -o "$tmpfile" --unicode-subst="<0x%x>" 2>/dev/null
        if [ $? -eq 0 ]; then
            mv -f "$tmpfile" "$file"
            echo "complete: $file (other → UTF-8)"
        else
            echo "failed '$file' 编码转换失败，已保留原文件和备份"
            rm -f "$tmpfile"
        fi
    fi
done


